package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffOutput;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.serializer.Serializer;

import java.io.IOException;

public final class ISchemaProtostuffSerializer<T> implements Serializer<T> {
    public static final byte[] EMPTY = new byte[0];
    private final ISchema schema;

    public ISchemaProtostuffSerializer(ISchema schema) {
        this.schema = schema;
    }

    @Override
    public byte[] serialize(T data) {
        if (data == null) {
            return EMPTY;
        }
        try {
            LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            ProtostuffOutput output = new ProtostuffOutput(buffer);
            schema.write(output, 1, data, false);
            return output.toByteArray();
        } catch (IOException e) {
            throw new ZoomException(e);
        }
    }

    @Override
    public T deserialize(byte[] bytes) {
        try {
            if (bytes == null || bytes.length == 0) {
                return null;
            }
            ByteArrayInput input = new ByteArrayInput(bytes, 0, bytes.length, true);
            input.readFieldNumber(null);
            return (T) schema.mergeFrom(input);
        } catch (IOException e) {
            throw new ZoomException(e);
        }
    }
}
